using UnityEditor;
using UnityEngine;

public class TriangleData
{
    public int Id;

    //三角形三个顶点(顺时针)
    public Vector3 A;
    public Vector3 B;
    public Vector3 C;

    //寻路用
    public TriangleData NeighborA;
    public TriangleData NeighborB;
    public TriangleData NeighborC;
    public TriangleData Father;
    public TriangleData Next;
    public float F;
    public float H;
    public float G;
    public bool Finished;

    public void Reset()
    {
        F = 0f;
        H = 0f;
        G = 0f;
        NeighborA = null;
        NeighborB = null;
        NeighborC = null;
        Father = null;
        Next = null;
        Finished = false;
    }

    public Vector3 GetCenterPosition()
    {
        float a = (B - C).magnitude;
        float b = (B - C).magnitude;
        float c = (B - C).magnitude;

        Vector3 Center = new Vector3((a * A.x + b * B.x + c * C.x) / (a + b + c),
            (a * A.y + b * B.y + c * C.y) / (a + b + c),
            (a * A.z + b * B.z + c * C.z) / (a + b + c));
        return Center;
    }

    public bool IsPointInTriangle(Vector3 p)
    {
        //忽略y轴
        var calA = new Vector3(A.x, 0, A.z);
        var calB = new Vector3(B.x, 0, B.z);
        var calC = new Vector3(C.x, 0, C.z);
        var calP = new Vector3(p.x, 0, p.z);

        //顺时针反向皆在右侧则在三角形内(AB-AP、BC-BP、CA-CP)
        if (Vector3.Cross(calB - calA, calP - calA).y < 0)
            return false;
        if (Vector3.Cross(calC - calB, calP - calB).y < 0)
            return false;
        if (Vector3.Cross(calA - calC, calP - calC).y < 0)
            return false;
        
        return true;
    }

    public void Draw(Color col)
    {
        Handles.color = col;
        Handles.DrawLine(A, B);
        Handles.DrawLine(B, C);
        Handles.DrawLine(C, A);
        
        // Handles.color = Color.red;
        // Handles.DrawLine(A+Vector3.up*Id, B+Vector3.up*Id);
        // Handles.color = Color.green;
        // Handles.DrawLine(B+Vector3.up*Id, C+Vector3.up*Id);
        // Handles.color = Color.blue;
        // Handles.DrawLine(C+Vector3.up*Id, A+Vector3.up*Id);
    }
}